package com.xunmall.engine.service.impl;

import com.xunmall.engine.entity.EmployeeDO;
import com.xunmall.engine.repository.EmployeeRepository;
import com.xunmall.engine.service.EmployeeService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author wangyanjing
 * @date 2018/9/11
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public long count() {
        return employeeRepository.count();
    }

    @Override
    public EmployeeDO save(EmployeeDO employeeDO) {
        return employeeRepository.save(employeeDO);
    }

    @Override
    public void delete(EmployeeDO employeeDO) {
        employeeRepository.delete(employeeDO);
    }

    @Override
    public Iterable<EmployeeDO> getAll() {
        return employeeRepository.findAll();
    }

    @Override
    public List<EmployeeDO> getByName(String name) {
        List<EmployeeDO> list = new ArrayList<>();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("name", name);
        Iterable<EmployeeDO> iterable = employeeRepository.search(matchQueryBuilder);
        iterable.forEach(item -> list.add(item));
        return list;
    }

    @Override
    public Page<EmployeeDO> pageQuery(Integer pageNo, Integer pageSize, String kw) {
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("name", kw))
                .withPageable(new PageRequest(pageNo, pageSize))
                .build();
        return employeeRepository.search(searchQuery);
    }
}
